package com.zareal.ymcc.consumer;


import com.alibaba.fastjson.JSONObject;
import com.zareal.ymcc.domain.MessageSms;
import com.zareal.ymcc.dto.MessageSmsDto;
import com.zareal.ymcc.dto.UserSmsDto;
import com.zareal.ymcc.service.IMessageSmsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

import static com.zareal.ymcc.constans.MqConstants.COURSE_SMS_TAG;
import static com.zareal.ymcc.constans.MqConstants.COURSE_SMS_TOPIC;
/**
 * @BelongsProject: itsource-ymcc
 * @BelongsPackage: cn.itsource.consumer
 * @Author: Director
 * @CreateTime: 2022-09-07  23:18
 * @Description: 短信消息推送mq消费方
 * @Version: 1.0
 */
@Slf4j
@Component
@RocketMQMessageListener(
        consumerGroup = "message-sms-group",
        topic = COURSE_SMS_TOPIC,
        selectorExpression = COURSE_SMS_TAG
)
public class MessageSmsConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private IMessageSmsService messageSmsService;

    @Override
    public void onMessage(MessageExt messageExt) {
        // 1.获取消息体，如果为空，那么不消费消息
        byte[] body = messageExt.getBody();
        if (body == null || body.length == 0){
            return;
        }
        // 2.转换消息体
        MessageSmsDto messageSmsDto = JSONObject.parseObject(new String(body, StandardCharsets.UTF_8), MessageSmsDto.class);
        // 3.保存消息到数据库
        saveMessageSms(messageSmsDto);
        // 4.@TODO 调用短信服务群发消息
        List<UserSmsDto> users = messageSmsDto.getUsers();
        for (UserSmsDto user : users) {
            System.out.printf("发送短信成功，消息标题为：%s, 消息内容为：%s, 用户电话为：%s\n", messageSmsDto.getTitle(), messageSmsDto.getContent(), user.getPhone());

        }
    }

    /*
     * @Description: 保存短信消息到数据库
     * @Author: Director
     * @Date: 2022/9/7 23:25
     * @param messageSmsDto: 短信mq消息对象
     * @return: void
     **/
    private void saveMessageSms(MessageSmsDto messageSmsDto) {
        // 1.获取数据
        String title = messageSmsDto.getTitle();
        String content = messageSmsDto.getContent();
        List<UserSmsDto> users = messageSmsDto.getUsers();
        // 2.初始化参数
        MessageSms messageSms = new MessageSms();
        messageSms.setTitle(title);
        messageSms.setContent(content);
        messageSms.setSendTime(new Date());
        // 3.遍历设置用户id，并保存数据
        users.forEach(e->{
            messageSms.setUserId(e.getId());
            messageSmsService.insert(messageSms);
        });
    }
}